package com.lagou.service;

import com.lagou.encoder.RpcDecoder;
import com.lagou.handler.UserServiceHandler;
import com.lagou.request.RpcRequest;
import com.lagou.serializer.JSONSerializer;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringEncoder;
import org.apache.curator.RetryPolicy;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.retry.ExponentialBackoffRetry;
import org.apache.zookeeper.CreateMode;
import org.springframework.stereotype.Service;

@Service("userService")
//@Component
public class UserServiceImpl implements IUserService {

    //将来客户单要远程调用的方法
   /* public String sayHello(String msg) {
        System.out.println("are you ok ? "+msg);
        return "服务器返回数据 : "+msg;
    }*/

    @Override
    public String sayHello(RpcRequest rpcRequest) {
        System.out.println("服务器端1接收的数据为："+rpcRequest);
        return "服务器端1返回：success";
    }
    //创建一个方法启动服务器
    public static void startServer(String ip , int port) throws Exception {
        //1.创建两个线程池对象
        NioEventLoopGroup  bossGroup = new NioEventLoopGroup();
        NioEventLoopGroup  workGroup = new NioEventLoopGroup();

        //2.创建服务端的启动引导对象
        ServerBootstrap serverBootstrap = new ServerBootstrap();

        //3.配置启动引导对象
        serverBootstrap.group(bossGroup,workGroup)
                //设置通道为NIO
                .channel(NioServerSocketChannel.class)
                //创建监听channel
                .childHandler(new ChannelInitializer<NioSocketChannel>() {
                    protected void initChannel(NioSocketChannel nioSocketChannel) throws Exception {
                        //获取管道对象
                        ChannelPipeline pipeline = nioSocketChannel.pipeline();
                        //给管道对象pipeLine 设置编码
                        pipeline.addLast(new StringEncoder());
                        pipeline.addLast(new RpcDecoder(RpcRequest.class,new JSONSerializer()));
                        //把我们自顶一个ChannelHander添加到通道中
                        pipeline.addLast(new UserServiceHandler());
                    }
                });

        //4.绑定端口
        serverBootstrap.bind(port).sync();
        //注册 IP 端口到zk
        updateZK(ip,port);
    }

    public static void updateZK(String ip , int port) throws Exception {
        RetryPolicy exponentialBackoffRetry = new ExponentialBackoffRetry(1000, 3);

        // 使用fluent编程风格
        CuratorFramework client = CuratorFrameworkFactory.builder()
                .connectString("127.0.0.1:2181")
                .sessionTimeoutMs(50000)
                .connectionTimeoutMs(30000)
                .retryPolicy(exponentialBackoffRetry)
                .namespace("rpc")  // 独立的命名空间 /base
                .build();

        client.start();

        System.out.println("服务端1ZK创建成功");

        // 创建节点
        String path = "/rpc-provider/s1";
        if(client.checkExists().forPath(path) ==  null) {
            String s = client.create().creatingParentsIfNeeded()
                    .withMode(CreateMode.EPHEMERAL_SEQUENTIAL).forPath(path, (ip + ":" + port).getBytes());

            System.out.println("服务1节点创建成功，该节点路径" + s);
        }
    }


}
